﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using PSE.Framework.Common.Security.Services.Authentication.ClientCredentials;

namespace PSE.Framework.UI.Security.Authentication
{
    /// <summary>
    /// Classe singleton responsável por gerenciar questões de autenticação
    /// </summary>
    public class AuthenticationManager
    {
        private static Mutex _mtx = new Mutex();
        private static AuthenticationManager _instance = null;

        private IAuthenticationProvider _authenticationProvider = null;

        public CustomClientCredentials ClientCredentials
        {
            get
            {
                return _authenticationProvider.GetClientCredentials();
            }
        }

        private AuthenticationManager()
        {
            //carregar o provider de autenticacao
            _authenticationProvider = AuthenticationProviderFactory.CreateProvider();
        }

        public static AuthenticationManager GetInstance()
        {
            try
            {
                _mtx.WaitOne();

                if (_instance == null)
                    _instance = new AuthenticationManager();
            }
            catch
            {
                throw;
            }
            finally
            {
                _mtx.ReleaseMutex();
            }

            return _instance;
        }

        /// <summary>
        /// Autenticar sem informar uma credencial padrão
        /// </summary>
        /// <returns></returns>
        public bool Authenticate()
        {
            return _authenticationProvider.Authenticate();
        }


        /// <summary>
        /// Autenticar informando uma credencial padrão
        /// </summary>
        /// <param name="credentials">Credenciais utilizadas na autenticação</param>
        /// <returns></returns>
        public bool Authenticate(CustomClientCredentials credentials)
        {
            return _authenticationProvider.Authenticate(credentials);
        }
    }
}
